package cn.itcast.star.graph.core.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.jwt.JWT;
import cn.itcast.star.graph.core.pojo.User;

public class JwtUtils {

    private static final String JWT_SECRET = "waibibabu";

    public static String createJwt(Long id, String name) {

        return JWT.create()
                .setPayload("uid", id)
                .setPayload("username", name)
                .setExpiresAt(DateTime.now().offset(DateField.YEAR, 1))
                .setKey(JWT_SECRET.getBytes())
                .sign();
    }

    public static boolean verify(String token) {
        try {
           return JWT.of(token).setKey(JWT_SECRET.getBytes()).verify();

        } catch (Exception e) {
            return false;
        }
    }

    public static User getUser(String token) {
        try {
            JWT jwt = JWT.of(token).setKey(JWT_SECRET.getBytes());
            User user = new User();
            user.setId(jwt.getPayload("uid") == null ? null
                    : NumberUtil.parseLong(jwt.getPayload("uid").toString()));
            user.setUsername(jwt.getPayload("username").toString());
            return user;
        } catch (Exception e) {
            return null;
        }
    }
}
